/*
 * @Descripttion: 
 * @Author: mayuanzheng
 * @Date: 2020-12-14 15:24:13
 * @LastEditors: mayuanzheng
 * @LastEditTime: 2021-03-05 16:01:01
 */
// https://github.com/imagemin
const imagemin = require('imagemin'); 
const imageminJpegRecompress = require('imagemin-jpeg-recompress');
const imageminPngquant = require('imagemin-pngquant');
const imageminGifsicle = require('imagemin-gifsicle');
const imageminSvgo = require('imagemin-svgo');
const imageminWebp = require('imagemin-webp');
// const imageminGif2webp = require('imagemin-gif2webp'); //TODO:不生效还报错

const chalk = require('chalk');
const path=require('path');
const fs = require("fs");

let PATH = "";
let OUT_PATH = "";
const SupportSuffix = ['.jpg','.jpeg','.png','.gif','.svg'];
const UnSupportFile = ['node_modules','.DS_Store','.git','.vscode'];
let Quality = 80;
let WebpQuality = false;
let Plugins = [];
function getPlugins(){
    let _plugins = [
        imageminJpegRecompress({
            quality: 'high',
            min: Quality-10,
            max: Quality+10,
            method: "smallfry"
        }),
        imageminPngquant({
            quality: [Quality/100-0.1, Quality/100+0.1]
        }),
        imageminSvgo({
            plugins: [
                {removeViewBox: false}
            ]
        }),
        imageminGifsicle({
            optimizationLevel: Math.ceil(Quality/34),
        }),
    ]
    if(WebpQuality){
        _plugins.push(imageminWebp({quality: WebpQuality})); //这个转成webp的参数对图片清晰度影响较大
    }
    return _plugins
}

/**
 * 主入口
 */
async function main(cmd){
        PATH = process.cwd()+(cmd.path?('/'+cmd.path):'');
        OUT_PATH = process.cwd()+'/'+(cmd.outpath||(cmd.path?cmd.path+'_output':'output'))

        Quality = parseInt(cmd.quality,10) || Quality; 
        if(Quality<10) Quality = Quality*10; //默认是百分制，也可以支持十分制
        if(Quality>90) Quality = 90;

        if(cmd.webp){
            WebpQuality = parseInt(cmd.webp,10) || 80;
            if(WebpQuality<10) WebpQuality = WebpQuality*10; 
            if(WebpQuality>100) WebpQuality = 100;
        }
         
        Plugins = getPlugins();
        console.log(chalk.green(`读取文件目标文件夹: ${PATH}`))
        console.log(chalk.green(`生成图片文件夹: ${OUT_PATH}`))
        console.log(chalk.green(`图片压缩质量: ${Quality}`))
        WebpQuality && console.log(chalk.green(`转成webp质量: ${WebpQuality}`))
        compress(PATH);
}

function compress(imgpath){
    fs.readdir(imgpath, function(err, files){     
        if(err){
            console.log('error' + err);
            return;
        }
        //console.log('files:' + files);
        files.forEach(function(file){
            var imgName = imgpath + '/' + file;
            fs.stat(imgName, function(err, stat){
                if(err){console.log(err); return;}
                //过滤不支持的文件
                if(UnSupportFile.includes(file)) return;
                //如果是文件夹遍历
                if(stat.isDirectory()){        
                    compress(imgName);
                }else{ 
                    //过滤不支持的后缀
                    if(!SupportSuffix.includes(path.extname(file))) return;

                    // console.log('文件:' + imgName);

                    //直接遍历图片的写法，但是只能遍历1层
                    // imagemin([imgpath+'/*.{jpg,jpeg,png,gif,svg}'], {
                    imagemin([imgName], {
                        destination: OUT_PATH,
                        plugins: Plugins,
                    }).then(res=>{
                        res.map(i=>console.log(chalk.blue(i.destinationPath)))
                    }).catch(err=>{
                        console.log(chalk.red(err))
                    });

                }               
            });

        });

    });
}
 
module.exports = main;